//
//  WFBProViewController.swift
//  iiatn
//
//  Created by mine on 18/4/17.
//  Copyright © 2018年 mnine. All rights reserved.
//

import UIKit
import SVProgressHUD

class WFBProViewController: itBaseViewController, UITextViewDelegate {

    @IBOutlet var protitle: UITextField!
    
    @IBOutlet var proamount: UITextField!
    
    //@IBOutlet var prodiyu: UITextField!
    
    //@IBOutlet var prohangye: UITextField!
    
    @IBOutlet var prodescription: UITextView!
    
    @IBOutlet var procontent: UITextView!
    
    @IBOutlet var storebtn: UIButton!
    
    @IBOutlet var meiyuan: UILabel!
    
    @IBOutlet var hangye: UILabel!
    
    var texts = [UITextField]()
    
    var catid = 1
    
    var fil = ["",""]
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.addGestureRecognizer(UITapGestureRecognizer(target:self, action:#selector(self.handleTap(sender:))))
        prodescription.delegate = self
        procontent.delegate = self
        setstyle()
        setdrop()
        setdosth()

    }

    override func setupNav() {
        view.backgroundColor = UIColor.white
    }
    func setstyle(){
        
        hangye.x = SCREENW/2
        
        texts.append(protitle)
        texts.append(proamount)
        //texts.append(prodiyu)
        //texts.append(prohangye)
        
        meiyuan.x = SCREENW - 86
        
        for text in texts {
            text.layer.borderWidth = 0.5
            text.layer.borderColor = UIColor.gray.cgColor
            text.width = SCREENW - 114
            text.layer.cornerRadius = text.height * 0.2
            text.layer.masksToBounds = true
            text.layer.rasterizationScale = UIScreen.main.scale
        }
        proamount.width = proamount.width - 68
        
        prodescription.layer.borderWidth = 0.6
        prodescription.layer.borderColor = UIColor.gray.cgColor
        prodescription.width = SCREENW - 114
        prodescription.layer.cornerRadius = prodescription.height * 0.1
        prodescription.layer.masksToBounds = true
        prodescription.layer.rasterizationScale = UIScreen.main.scale
        prodescription.text = "请输入项目简述（选题）"
        prodescription.textColor = UIColor.lightGray
        prodescription.tag = 1
        
        procontent.layer.borderWidth = 0.6
        procontent.layer.borderColor = UIColor.gray.cgColor
        procontent.width = SCREENW - 114
        procontent.layer.cornerRadius = procontent.height * 0.1
        procontent.layer.masksToBounds = true
        procontent.layer.rasterizationScale = UIScreen.main.scale
        procontent.text = "请输入项目内容（必填）"
        procontent.textColor = UIColor.lightGray
        procontent.tag = 2
        
        storebtn.width = SCREENW - 64
        storebtn.layer.cornerRadius = storebtn.height * 0.13
        storebtn.layer.masksToBounds = true
        storebtn.layer.rasterizationScale = UIScreen.main.scale
    }
    
    func setdrop(){
        let drop1 = getLanmu()
        let drop2 = getGb()
        let drop3 = getHy()
        
        view.addSubview(drop1)
        view.addSubview(drop2)
        view.addSubview(drop3)
    }
    
    func setdosth(){
        storebtn.addTarget(self, action: #selector(tryfb), for: .touchUpInside)
    }
    
    func tryfb(){
        var trygo = true
        if (protitle.text?.isEmpty)! {
            trygo = false
            SVProgressHUD.showError(withStatus: "标题不能为空！")
            return
        }
        if !(proamount.text?.isEmpty)! && !isPurnFloat(string: proamount.text!) {
            trygo = false
            SVProgressHUD.showError(withStatus: "金额只能为数字！")
            return
        }
        if procontent.textColor == UIColor.lightGray {
            trygo = false
            SVProgressHUD.showError(withStatus: "内容不能为空！")
            return
        }
        
        if trygo {
            if (proamount.text?.isEmpty)! {
                proamount.text = "0"
            }
            dofb()
        }
    
    }
    func dofb(){
        
        switch fil[0] {
        case "亚洲：日本":
            fil[0] = "日本"
            break
        case "欧洲：英国":
            fil[0] = "英国"
            break
        case "非洲：尼日利亚":
            fil[0] = "尼日利亚"
            break
        case "大洋洲：澳大利亚":
            fil[0] = "澳大利亚"
            break
        case "北美洲：美国":
            fil[0] = "美国"
            break
        case "南美洲：巴西":
            fil[0] = "巴西"
            break
        default:
            break
        }
        
        
        let filterattr = "\(fil[0])|\(fil[1])"
        
        //print(filterattr)
        //print(catid)

        WNetwork.shareNetworkTool.createPro(uid: wuserid!, catid: catid,title: protitle.text!, description: prodescription.text!, filterattr_value: filterattr, amount_money: Int(proamount.text!)!, content: procontent.text!){ (msg) in
            print("fb success!")
            DispatchQueue.main.asyncAfter(deadline: .now() + 1.2) {self.navigationBackClick()}
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    func textViewDidBeginEditing(_ textView: UITextView) {
        if textView.textColor == UIColor.lightGray {
            textView.text = nil
            textView.textColor = UIColor.black
        }
        if textView.tag == 2 {
            UIView.animate(withDuration: 0.5) {
                self.view.transform = CGAffineTransform(translationX: 0, y: -200)
            }
        }
    }
    func textViewDidEndEditing(_ textView: UITextView) {
        if textView.text.isEmpty {
            if textView.tag == 1 {
                textView.text = "请输入项目简述（选填）"
            }else {
                textView.text = "请输入项目内容（必填）"
            }
            textView.textColor = UIColor.lightGray
        }
        if textView.tag == 2 {
            UIView.animate(withDuration: 0.5) {
                self.view.transform = CGAffineTransform(translationX: 0, y:0)
            }
        }
    }
    
    /// 返回按钮
    func navigationBackClick() {
        if UIApplication.shared.isNetworkActivityIndicatorVisible {
            UIApplication.shared.isNetworkActivityIndicatorVisible = false
        }
        let back_now = navigationController?.popViewController(animated: true)
        print("发布项目后返回：\(back_now)")
    }
    
    func isPurnFloat(string: String) -> Bool {
        let scan: Scanner = Scanner(string: string)
        var val:Float = 0
        return scan.scanFloat(&val) && scan.isAtEnd
    }
    func handleTap(sender: UITapGestureRecognizer) {
        if sender.state == .ended {
            for text in texts {
                text.resignFirstResponder()
            }
            prodescription.resignFirstResponder()
            procontent.resignFirstResponder()
        }
        sender.cancelsTouchesInView = false
    }
    
    
    
    func getLanmu() -> TGDropBoxView {
        let defaultTitle = "请选择栏目[默认海外投资]"
        let choices = ["海外投资", "全球基础设施合作", "境外园区", "国际产能合作",
            "咨询服务", "走出去服务", "招投标信息",
            "海外安保", "人才培训", "法律服务","审计服务", "翻译服务"]
        let choices_num = [1,2,4,5,40,25,43,6,7,37,38,44]
        
        let rect = CGRect(x: 82, y: 165, width: SCREENW - 114, height: 30)
        let dropBoxView = TGDropBoxView(parentVC: self, title: defaultTitle, items: choices, frame: rect)
        dropBoxView.isHightWhenShowList = true
//        dropBoxView.willShowOrHideBoxListHandler = { (isShow) in
//            if isShow { NSLog("will show choices") }
//            else { NSLog("will hide choices") }
//        }
//        dropBoxView.didShowOrHideBoxListHandler = { (isShow) in
//            if isShow { NSLog("did show choices") }
//            else { NSLog("did hide choices") }
//        }
        dropBoxView.didSelectBoxItemHandler = { (row) in
            NSLog("selected No.\(row): \(dropBoxView.currentTitle())")
            print(choices_num[row])
            self.catid = choices_num[row]
        }
        
        dropBoxView.layer.borderWidth = 0.6
        dropBoxView.layer.borderColor = UIColor.gray.cgColor
        dropBoxView.layer.cornerRadius = dropBoxView.height * 0.1
        dropBoxView.layer.masksToBounds = true
        dropBoxView.layer.rasterizationScale = UIScreen.main.scale
        
        return dropBoxView
    }
    
    func getHy() -> TGDropBoxView {
        
        let defaultTitle = "行业选择"
        let choices = ["农林牧渔", "能源资源", "制造业", "商贸物流", "技术研发",
                       "文化旅游", "房地产及建筑", "保险金融",
                       "其他"]
        let choices_num = [1,2,3,7,8,9,10,11,209]
        
        let rect = CGRect(x: Int(SCREENW/2+50), y: 200, width: Int(SCREENW)/2 - 85, height: 30)
        let dropBoxView = TGDropBoxView(parentVC: self, title: defaultTitle, items: choices, frame: rect)
        dropBoxView.isHightWhenShowList = true
//        dropBoxView.willShowOrHideBoxListHandler = { (isShow) in
//            if isShow { NSLog("will show choices") }
//            else { NSLog("will hide choices") }
//        }
//        dropBoxView.didShowOrHideBoxListHandler = { (isShow) in
//            if isShow { NSLog("did show choices") }
//            else { NSLog("did hide choices") }
//        }
        dropBoxView.didSelectBoxItemHandler = { (row) in
            NSLog("selected No.\(row): \(dropBoxView.currentTitle())")
            print(choices_num[row])
            self.fil[1]=choices[row]
        }
        
        dropBoxView.layer.borderWidth = 0.6
        dropBoxView.layer.borderColor = UIColor.gray.cgColor
        dropBoxView.layer.cornerRadius = dropBoxView.height * 0.1
        dropBoxView.layer.masksToBounds = true
        dropBoxView.layer.rasterizationScale = UIScreen.main.scale
        
        return dropBoxView
    }
    
    
    func getGb() -> TGDropBoxView {
        let defaultTitle = "地域选择"
        
        let gbs = [["22","亚洲：日本"],["30","印度"],["158","马来西亚"],["173","新加坡"],["204","巴基斯坦"],["180","印度尼西亚"],["167","泰国"],["31","孟加拉"],["21","韩国"],["19","蒙古国"],["20","朝鲜"],["126","阿富汗"],["127","阿拉伯联合酋长国"],["128","阿曼"],["129","阿塞拜疆"],["136","巴林"],["141","东帝汶"],["142","菲律宾"],["143","格鲁吉亚"],["144","哈萨克斯坦"],["145","吉尔吉斯斯坦"],["147","柬埔寨王国"],["148","卡塔尔"],["150","科威特"],["152","老挝"],["153","黎巴嫩"],["156","马尔代夫"],["160","缅甸"],["161","尼泊尔"],["163","沙特阿拉伯"],["165","斯里兰卡"],["166","塔吉克斯坦"],["168","土耳其"],["169","土库曼斯坦"],["170","文莱"],["171","乌兹别克斯坦"],["174","叙利亚"],["175","亚美尼亚"],["176","也门"],["177","伊拉克"],["178","伊朗"],["179","以色列"],["181","约旦"],["182","越南"],["205","不丹"],["5","欧洲：英国"],["151","德国"],["29","俄罗斯"],["199","西班牙"],["17","法国"],["202","意大利"],["190","葡萄牙"],["200","希腊"],["13","爱尔兰"],["14","荷兰"],["15","比利时"],["16","卢森堡"],["32","波兰"],["131","阿尔巴尼亚"],["133","爱沙尼亚"],["135","奥地利"],["137","白俄罗斯"],["139","保加利亚"],["140","冰岛"],["146","波黑"],["149","丹麦"],["154","芬兰"],["157","捷克"],["159","克罗地亚"],["162","拉脱维亚"],["164","立陶宛"],["184","罗马尼亚"],["185","马耳他"],["186","马其顿"],["187","摩尔多瓦"],["189","挪威"],["191","瑞典"],["192","瑞士"],["194","塞浦路斯"],["196","斯洛伐克"],["197","斯洛文尼亚"],["198","乌克兰"],["201","匈牙利"],["203","塞尔维亚"],["86","非洲：尼日利亚"],["25","埃及"],["26","南非"],["33","阿尔及利亚"],["34","埃塞俄比亚"],["35","安哥拉"],["36","贝宁"],["37","博兹瓦纳"],["38","布基纳法索"],["39","布隆迪"],["40","赤道几内亚"],["41","多哥"],["42","厄立特里亚"],["43","佛得角"],["45","刚果（布）"],["46","刚果（金）"],["47","吉布提"],["48","几内亚"],["49","几内亚比绍"],["51","加纳"],["53","加蓬"],["55","津巴布韦"],["58","喀麦隆"],["66","科摩罗"],["70","科特迪瓦"],["71","肯尼亚"],["72","莱索托"],["73","利比里亚"],["74","利比亚"],["75","卢旺达"],["76","马达加斯加"],["77","马拉维"],["78","马里"],["79","毛里求斯"],["80","毛里塔尼亚"],["81","摩洛哥"],["82","莫桑比克"],["83","纳米比亚"],["84","南苏丹"],["85","尼日尔"],["87","塞拉利昂"],["88","塞内加尔"],["89","塞舌尔"],["92","苏丹"],["93","索马里"],["94","坦桑尼亚"],["95","突尼斯"],["96","乌干达"],["97","赞比亚"],["98","乍得"],["99","中非"],["27","大洋洲：澳大利亚"],["28","新西兰"],["100","巴布亚新几内亚"],["101","斐济"],["103","密克罗尼西亚"],["106","萨摩亚"],["108","瓦努阿图"],["110","汤加"],["50","北美洲：美国"],["52","加拿大"],["69","墨西哥"],["54","安提瓜和巴布达"],["56","巴巴多斯"],["57","巴哈马"],["59","巴拿马"],["62","多米尼克国"],["63","哥斯达黎加"],["64","格林纳达"],["65","古巴"],["68","洪都拉斯"],["112","特立尼达和多巴哥"],["114","牙买加"],["23","南美洲：巴西"],["24","阿根廷"],["121","秘鲁"],["125","智利"],["116","巴拉圭"],["117","玻利维亚"],["118","厄瓜多尔"],["119","哥伦比亚"],["120","圭亚那"],["122","苏里南"],["123","委内瑞拉"],["124","乌拉圭"]]
        
        
        
        var choices = [String]()
        var choices_num = [Int]()
        
        var gbi = 0
        for gb in gbs{
            choices.append(gb[1])
            choices_num.append(Int(gb[0])!)
            gbi = gbi + 1
        }
        
        
        let rect = CGRect(x: 82, y: 200, width: Int(SCREENW)/2 - 86, height: 30)
        let dropBoxView = TGDropBoxView(parentVC: self, title: defaultTitle, items: choices, frame: rect)
        dropBoxView.isHightWhenShowList = true
//        dropBoxView.willShowOrHideBoxListHandler = { (isShow) in
//            if isShow { NSLog("will show choices") }
//            else { NSLog("will hide choices") }
//        }
//        dropBoxView.didShowOrHideBoxListHandler = { (isShow) in
//            if isShow { NSLog("did show choices") }
//            else { NSLog("did hide choices") }
//        }
        dropBoxView.didSelectBoxItemHandler = { (row) in
            NSLog("selected No.\(row): \(dropBoxView.currentTitle())")
            print(choices_num[row])
            self.fil[0]=choices[row]
        }
        
        dropBoxView.layer.borderWidth = 0.6
        dropBoxView.layer.borderColor = UIColor.gray.cgColor
        dropBoxView.layer.cornerRadius = dropBoxView.height * 0.1
        dropBoxView.layer.masksToBounds = true
        dropBoxView.layer.rasterizationScale = UIScreen.main.scale
        
        return dropBoxView
    }
    
    

}
